home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Magnum One
/
Magnum One (Mid-American Digital) (Disc Manufacturing).iso
/
d12
/
cgazv5n5.arc
/
EXPRESS.Y
< prev
next >
Wrap
Text File
|
1991-09-23
|
3KB
|
138 lines
%term ID /* a string of lower-case characters */
%term NUM /* a number */
%left PLUS /* + */
%left TIMES /* * */
%left LP RP /* ( ) */
%{
#include <stdio.h>
#include <ctype.h>
#include <malloc.h>
extern char *yytext; /* In yylex(), holds lexeme */
extern char *new_name(); /* declared at bottom of this file */
typedef char *stype; /* Type the value stack as char* */
#define YYSTYPE stype
%}
%%
/* A small expression grammar that recognizes numbers,names,
* addition (+), multiplication (*), and parentheses. Expressions
* associate left to right unless parentheses force it to go
* otherwise. + is lower precedence than *. Note that an
* underscore is appended to identifiers so that they won't be
* confused with temporary variables.
*/
s : e ;
e : e PLUS e {printf("%s += %s;\n", $1, $3); free_name($3 ); }
| e TIMES e {printf("%s *= %s;\n", $1, $3); free_name($3 ); }
| LP e RP {$$ = $2; }
| NUM {printf("%s = %s;\n", $$ = new_name(),yytext );}
| ID {printf("%s = _%s;\n", $$ = new_name(),yytext );}
;
%%
/*-------------------------------------------------------------*/
#ifdef OCCS
char *yypstk( ptr )
char **ptr;
{
/* Used only by occs, (not by UNIX yacc), yypstk()is used
* by the debugging version of the parser to print the value
* stack. It is passed a pointer to a value-stack item and
* should return a string representing that item. In this
* case, all it has to do is dereference one level of
* indirection.
*/
return *ptr ? *ptr : "<empty>" ;
}
#endif
/*-------------------------------------------------------------*/
char *Names[] = {"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"};
char **Namep = Names;
char *new_name()
{
/* Simplistic temporary-variable management. Return a
* temporary-variable name by popping one off the name stack.
*/
if( Namep >= &Names[ sizeof(Names)/sizeof(*Names) ] )
{
yyerror("Expression too complex\n");
exit( 1 );
}
return( *Namep++ );
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
free_name(s)
char *s;
{ /* Free up a previously allocated name */
*--Namep = s;
}
/*-------------------------------------------------------------*/
yy_init_occs()
{
/* Generate declarations for the temporary variables
printf("int t0, t1, t2, t3;\n");
printf("int t4, t5, t6, t7;\n");
}
/*-------------------------------------------------------------*/
main( argc, argv )
int argc;
char **argv;
{
yy_get_args( argc, argv );
if( argc < 2 )
{
fprintf( stderr, "Need file name\n");
exit(1);
}
#ifdef OCCS
else if( ii_newfile(argv[1]) << 0 )
#else /* UNIX yacc */
else if( !freopen( argv[1], "r", stdin ))
#endif
{
fprintf( stderr, "Can't open %s\n", argv[1] );
exit(2);
}
#ifndef OCCS
yy_init_occs();
#endif
yyparse();
exit( 0 );
}